new Vue({ 
    
  el: '#page',
  filters: {
    re4(text) {
        var t =  text.replace(/\s/g,'').replace(/\D/g,'').replace(/(\d{4})(?=\d)/g,"$1 ")
        return t
    }
  },
  data: {
    api:'http://192.168.10.156:8080/', // java api
    // api:'http://192.168.10.216:80/php_otc1.php?type=', // php api
    baseUrl:'#',//默认请求地址 3.0 现在为动态获取
    //order 为临时列表，需要app内展示订单信息，此处只是作为展示使用
    numberShow:false,alertShow:false,false:false,true:true,loading:false,mainShow:1,fade:'view',resultData:[],showArrow:false,time:15 * 1000,URL:'',
    name:'Apay 法币交易',merchantSign:'',requestTimestamp:'',paymentProductCode : '',currencyName: 'CNY',tradeType: '1',directionType:'1',quantity: '',coinName : 'USDT',
    orderPrice : '',sellPreData:[],sellPreShow:false,placeholder:'购买',order:[],value:'',number:'',
    paymentDetailDto:{
        account:'',
        bankBranch:'',
        mobile:'',
        paymentMethodCode:'',
        reallyName:'',
    },
    },
    created: function () { 
    $(".hides").show();
    if(!sessionStorage.getItem('order')){
        this.order = [];
    }else{
        this.order = JSON.parse(sessionStorage.getItem('order'))
    }
    clearInterval(this.getStatus);this.getStatus = null;
    this.showZero=false;
        this.loading = false;

    },
    mounted(){ 
    },
  methods: {
      //切换交易方向
      ChangedirectionType(type){
      $('.tradeType div').eq(type-1).addClass('active').siblings().removeClass('active')
      this.directionType = type;
      if(type == 1){
          this.placeholder = '购买';
      }else{
          this.placeholder = '出售';
          this.tradeType = 1;
      }
      this.value = '';
      this.number = '';
    },
    //切换购买方式
  ChangeTradeType(type){
      //console.log(type)
      this.tradeType = type;
      this.value = '';
      this.number = '';
  },
   
  //选择支付产品
  gopayFirst(){
      if(this.value == ''){
          if(this.directionType == 1){
              vant.Notify('请输入购买金额或数量')
          }else{
              vant.Notify('请输入出售数量')

          }
      }
      else{
          this.alertShow=true;
          if(this.tradeType==1){
              this.orderPrice = 0; //购买金额 
              this.quantity = this.value;
          }else{
              this.orderPrice = this.value; //购买金额 
              this.quantity = 0
          }
       }
       
  },
  onActionCancel() {
      
      //    this.alertShow = false; 
          
  },
  gopay(code){
        var that = this;
        this.requestTimestamp = Date.parse(new Date());
        this.paymentProductCode = code;
        this.merchantOrderCode = 'OTC'+Date.parse(new Date())+Math.ceil(Math.random()*10);
        vant.Toast.loading({
            message: '加载中...',
            forbidClick:true,
            duration:0,
            loadingType: 'spinner'
        });
        if(this.directionType == 1) //如果是买 走原来的流程
        {
            let data = {
                'coinName':this.coinName,
                'currencyName':this.currencyName,
                'orderPrice':this.orderPrice,
                'paymentProductCode':this.paymentProductCode,
                'quantity':this.quantity,
                'requestTimestamp':this.requestTimestamp,
                'tradeType':this.tradeType,
            };
            vant.Toast.loading({
                message: '加载中...',
                forbidClick:true,
                duration:0,
                loadingType: 'spinner'
            });
            $.ajax({
                type : "POST",
                contentType: "application/json;charset=UTF-8",
                url : that.api + 'payment/startToPay',
                data : JSON.stringify(data),
                success : function(result) {
                    console.log(result)
                    if(result.code != 200){
                        console.log(result)
                        vant.Toast.clear();
                        vant.Toast.fail({
                        message: result.message,
                            forbidClick:true,
                        });
                    }
                    else{
                        vant.Toast.clear();
                        that.resultData = result.data;
                        let res = result.data.initToPayment;
                        that.baseUrl = result.data.acceptPageUrl;
                        let data = 'billCode='+res.billCode+'&merchantId='+res.merchantId+'&merchantSign='+res.merchantSign+'&requestTimestamp='+res.requestTimestamp;
                        that.numberShow = false;
                        that.fade = 'viewleft'
                        that.mainShow = 3;
                        that.showArrow = true;
                        that.URL = that.baseUrl+'?'+data;
                        that.name = '下单成功，请支付';
                    }
                },
                error : function(e){
                    console.log(e);
                    vant.Toast.clear();
                    vant.Toast.fail({
                    message: '下单失败，请重试',
                        forbidClick:true,
                    });
                    
                }
            }); 
        }else if(this.directionType == 2){//如果是卖 
            if(this.tradeType == 1){
                var matchAmount = this.value;
                var matchPrice = 0;
            }else{
                var matchAmount = 0;
                var matchPrice = this.value;
            }
            let data = {
                'coinName':this.coinName,
                'currencyName':this.currencyName,
                'matchAmount':matchAmount,
                'matchPrice':matchPrice,
                'merchantId':this.merchantId, 
                'paymentProductCode':this.paymentProductCode,
                'requestTimestamp':this.requestTimestamp,
                'tradeType':this.tradeType,
                
            };
            //请求预览价格
            $.ajax({
                type : "POST",
                contentType: "application/json;charset=UTF-8",
                url : that.api + 'sellCoin/queryMatchingTotalPrice',
                data : JSON.stringify(data),
                success : function(result) {
                    if(result.code == '9999'){
                        //如果报错，处理错误
                        vant.Toast.clear();
                        vant.Toast.fail({
                        message: result.message,
                            forbidClick:true,
                        });
                    }
                    else{
                        vant.Toast.clear();
                        //成功后展示给客户看 确认金额
                        that.sellPreData = result.data; 
                        that.paymentDetailDto.paymentMethodCode  = that.sellPreData.methodCode
                        that.sellPreShow = true; 
                    }
                },
                //请求失败，处理失败
                error : function(e){
                    console.log(e);
                    vant.Toast.clear();
                    vant.Toast.fail({
                    message: '下单失败，请重试',
                        forbidClick:true,
                    }); 
                }
            }); 

        }else{
            vant.Toast.fail({
            message: '获取交易方向失败，请刷新页面或联系管理员',
                forbidClick:true,
            });
        } 
        
    },  
    //支付回调
    gopay3(){
        // vant.Dialog.confirm({
        //     title: '提示',
        //     message: '是否支付成功'
        //   }).then(() => {
        //     this.beforeClose();
        //   }).catch(() => {
        //     this.beforeClose();
        //   });
    },
    baroreSell(action, done){
        if (action === "confirm") {
            return done();
          } else {
            return done();
          }
    },
    goReSell(){
        this.sellPreShow = false;
        this.fade = 'viewleft'
        this.numberShow = false;
        this.mainShow = 2;
        this.showArrow = true;
        this.name = '请输入收款信息';
        


        // setTimeout(function(){
        //     that.sellPreShow = false;
        // }, 4000);
        //待签名 
    },
    onGoSell(){
        var that = this; 
        //避免后台报错空字符串 支付宝时传一个值
        if(this.sellPreData.methodCode == '0001'){
            var bankBranch = '0001'
        }else{
            var bankBranch = this.paymentDetailDto.bankBranch;
        }
        if(this.tradeType == 1){
            var sellAmount = this.value;
            var sellTotalPrice = 0;
        }else{
            var sellAmount = 0;
            var sellTotalPrice = this.value;
        }
        let data = {
            'account':this.paymentDetailDto.account,
            'bankBranch':bankBranch,
            'coinName':this.coinName,
            // 'currencyName':this.currencyName,
            'merchantId':this.merchantId, 
            'mobile':this.paymentDetailDto.mobile,
            'paymentProductCode':this.paymentProductCode,
            'reallyName':this.paymentDetailDto.reallyName,
            'requestTimestamp':this.requestTimestamp,
            'sellAmount':sellAmount,
            'sellTotalPrice':sellTotalPrice,
            'tradeType':this.tradeType,
        }; 
        vant.Toast.loading({
            message: '加载中...',
            forbidClick:true,
            duration:0,
            loadingType: 'spinner'
        });
        //请求预生成订单
        $.ajax({
            type : "POST",
            contentType: "application/json;charset=UTF-8",
            url : that.api + 'sellCoin/initialToSellCoin',
            data : JSON.stringify(data),
            success : function(result) {
                vant.Toast.clear();
                if(result.code == '9999'){
                    //如果报错，处理错误
                    vant.Toast.clear();
                    vant.Toast.fail({
                    message: result.message,
                        forbidClick:true,
                    });
                }
                else{
                    vant.Toast.clear();
                    that.orderData = {
                        'unitPrice':that.sellPreData.unitPrice,
                        'totalPrice':that.sellPreData.totalPrice,
                        'account':that.paymentDetailDto.account,
                        'bankBranch':bankBranch,
                        'coinName':that.coinName,
                        'currencyName':that.currencyName,
                        'merchantId':that.merchantId,
                        'merchantOrderCode':result.data.merchantOrderCode, 
                        'mobile':that.paymentDetailDto.mobile,
                        'methodCode':that.sellPreData.methodCode,
                        'paymentProductCode':that.paymentProductCode,
                        'reallyName':that.paymentDetailDto.reallyName,
                        'requestTimestamp':that.requestTimestamp,
                        'sellAmount':that.value,
                        'status':0,
                    }; 
                    var sessionOrder = that.order.reverse()
                    sessionOrder.push(that.orderData);
                    that.order = sessionOrder.reverse();
                    that.fade = 'viewleft'
                    that.mainShow = 4;
                    that.name = '成功！请等待买家支付后放币';
                    sessionStorage.setItem('order',JSON.stringify(that.order));
                }
            },
            error : function(e){
                console.log(e);
                vant.Toast.clear();
                vant.Toast.fail({
                message: '下单失败，请重试',
                    forbidClick:true,
                });
                
            }
        }); 
    },
    onClickLeft(){
        this.showArrow = false;
        this.fade = 'view'
        this.name = 'Apay 法币交易'
        this.numberShow = false;
        this.mainShow = 1;
        this.paymentDetailDto.account = '';
        this.paymentDetailDto.bankBranch = '';
        this.paymentDetailDto.mobile = '';
        this.paymentDetailDto.paymentMethodCode = '';
        this.paymentDetailDto.reallyName = '';

    },
    //打开订单列表
    openOrderList(){
        this.fade = 'viewleft';
        this.name = '订单列表';
        this.showArrow = true;
        this.numberShow = false;
        this.mainShow = 5;
    },
    //确认放币
    sellFinish(item){
        var that = this;
        vant.Dialog.confirm({
            title: '确认放币',
            message: '请确认收到付款，再点击放币',
            confirmButtonText:'放币',
            confirmButtonColor:'#EE0A24',
            cancelButtonText:'取消',
        })
        .then(() => {
            this.requestTimestamp = Date.parse(new Date());
            let data = {
                'merchantOrderCode':item.merchantOrderCode,  
                'requestTimestamp':this.requestTimestamp,
            };
            //请求预览价格
            $.ajax({
                type : "POST",
                contentType: "application/json;charset=UTF-8",
                url : that.api + 'sellCoin/confirmedReceiptAndCoinRelease',
                data : JSON.stringify(data),
                success : function(result) {
                    if(result.code == '9999'){
                        //如果报错，处理错误
                        vant.Toast.clear();
                        vant.Toast.fail({
                        message: result.message,
                            forbidClick:true,
                        });
                    }
                    else{
                        vant.Toast.clear();
                        vant.Toast.success({
                        message: '确认成功',
                            forbidClick:true,
                        });
                        that.showArrow = false;
                        that.fade = 'view'
                        that.name = 'Apay 法币交易'
                        that.numberShow = false;
                        that.mainShow = 1;
                        //交易成功后前端处理临时列表 正式接需要去掉 整个order的逻辑 和 sessionStorage
                        for(var i in that.order){
                            if(that.order[i].merchantOrderCode == item.merchantOrderCode){ 
                                that.order[i].status = 1;
                                sessionStorage.setItem('order',JSON.stringify(that.order.reverse()));
                            }
                        }
                    }
                },
                //请求失败，处理失败
                error : function(e){
                    console.log(e);
                    vant.Toast.clear();
                    vant.Toast.fail({
                    message: '放币失败，请重试',
                        forbidClick:true,
                    }); 
                }
            });
            
            // on confirm
        })
        .catch(() => {
            // on cancel
        });
    },
    
 
    gopayFirst(){
        if(this.value == ''){
            vant.Notify('请输入购买金额或数量')
        }
        else{
            this.alertShow=true;
            if(this.tradeType==1){
                this.orderPrice = 0; 
                this.quantity = this.value;
            }else{
                this.orderPrice = this.value;
                this.quantity = 0
            }
          
                               
            
         }
         
    },
    onActionCancel() {
        
    },
    
    beforeClose(action, done) {
        setTimeout(done, 1000);
    },
    onClickInputKeyBoard (val) {
        var that =this;
        var oldvalue = 0;
        var oldvalue = this.number + val
        if(this.tradeType==1){
            var newvalue = oldvalue.toString().match(/^\d*(\.?\d{0,9})/g)[0] || null
        }else{
            var newvalue = oldvalue.toString().match(/^\d*(\.?\d{0,2})/g)[0] || null
        }
        this.value = newvalue;
        setTimeout(function(){
            that.number = newvalue;
        },10);
        this.$forceUpdate();

      },
      onDeleteKeyBoard () {
        let flag = true
        if (flag) {
          this.value = this.value.substring(0, this.value.length - 1)
          this.number = this.value.substring(0, this.value.length - 1)
          if (this.value.length === 0) {
            flag = false
            return false
          }
        }
    }
  },

}); 
